/*
 * timer.c
 *
 * Created: 27.11.2012 12:49:23
 *  Author: Stefan
 */ 

/*
 * timer0_demo.c
 * Author: Dimitar
 */ 

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/io.h>
#include "timer.h"
#include <stdint.h>

#define T0_CLOCK_OFF				0x00
#define T0_CLOCK_FIO				0x01
#define T0_CLOCK_FIO8				0x02
#define T0_CLOCK_FIO64				0x03
#define T0_CLOCK_FIO256				0x04
#define T0_CLOCK_FIO1024			0x05
#define T0_CLOCK_EXT_FALLING_EDGE	0x06
#define T0_CLOCK_EXT_RISING_EDGE	0x07

// timer0 initialization
void init_Timer0() {
	//enable global interrupts
	sei();
	
	// pin 4 on port B (PB4/OC0B) set as output
	DDRB = (1 << DDB4);
	
	TCCR0A |= (1 << WGM01)  | (0 << WGM00);  // CTC mode Top: OC0A
	TCCR0A |= (0 << COM0B1) | (1 << COM0B0);	 // toggle OC0B pin
	//TCCR0B |= (1 << FOC0B);
	
	TCCR0B |= (1 << CS00); // clock = fcpu
	
	// CTC period settings
	OCR0A = 199; // reset every 199 timer ticks to get a frequency of 40kHz (8 MHz / 40KHz)
	OCR0B = 199;
	
	//Analog Comparator
	ACSR = (1 << ACIS1) | (0 << ACIS0) | (1 << ACIE); // Generate interrupt on falling edge
	
	// set interrupt masks
	TIMSK0 =  (1<< OCIE0B)   // disable  interrupt on compare match B
			 |(0 << OCIE0A)  // enable interrupt on compare-match A
			 |(0 << TOIE0);  // disable timer overflow interrupt
			 
}

void Ping(unsigned char length)
{
	count72kHz = 0;

	//Turn on AC
	ACSR &= ~(1 << ACD);
	//Toggle OC0B on Compare Match with OCR0B
	TCCR0A = (0 << COM0B1) | (1 << COM0B0);	 // toggle OC0B pin
	
	delay_ms(100);
	// generate the Chirp

	OCR0A = 190;

	//Turn off Toggling of OC0B on Compare Match
	//TCCR0A = (0 << COM0B0) | (0 << COM0B1);
	//OCR0B = 199;													// set frequency to 40kHz
}